Homework 5
Q1: Infinite Hailstone
写一个生成器函数来生成从n开始的冰雹猜想序列,当到达序列尾后,生成器会一直声称1
1 | def hailstone(n): |
使用递归,结合yield from生成迭代器
Q2: Merge
写一个merge函数,传入两个无限生成器a,b按照给定起始位置与步长生成非重复上升序列,返回一个生成器包含两个生成器中的所有元素,且去重
1 | def merge(a, b): |
Q3: Yield Paths
定义一个生成器函数,传入一棵树与一个值v,返回生成器从树的根到含有v的节点的每一条路径
1 | def yield_paths(t, value): |
If our current label is equal to
value, we’ve found a path from the root to a node containingvaluecontaining only our current label, so we should yield that. From there, we’ll see if there are any paths starting from one of our branches that ends at a node containingvalue. If we find these “partial paths” we can simply add our current label to the beginning of a path to obtain a path starting from the root.In order to do this, we’ll create a generator for each of the branches which yields these “partial paths”. By calling
yield_pathson each of the branches, we’ll create exactly this generator! Then, since a generator is also an iterable, we can iterate over the paths in this generator and yield the result of concatenating it with our current label.